<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" >
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card列表 -->
    <el-card class="box-card">
      <!-- addForm部分 -->
      <el-row :gutter="20" class="content">
        <el-col :span="8">
          <el-input placeholder="请输入内容" 
            v-model="queryobj.query"
            clearable
            @clear="getTableData">
            <el-button slot="append" icon="el-icon-search" @click="getTableData"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
     
      <!-- table部分 -->
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%">
        <el-table-column  type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="性名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch 
              v-model="scope.row.mg_state" 
              @change="updateStatus(scope.row.id,scope.row.mg_state)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button 
              type="primary" 
              icon="el-icon-edit" 
              size="mini" 
              @click="saveEditMessage(scope.row.id)"></el-button>
            <!-- 删除 -->
            <el-button 
              type="success" 
              icon="el-icon-delete" 
              size="mini"
              @click="deleteMessage(scope.row.id)"
            ></el-button>
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button 
                type="warning"
                icon="el-icon-setting" 
                size="mini"
                @click="disRoles(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

    <!-- 分页器部分 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="queryobj.pagesize"
      :current-page="queryobj.pagenum"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalpage">
    </el-pagination>
    </el-card>
    
    <!-- adddialog部分 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form  
        :model="dialogRuleForm" 
        :rules="dialogRules"
        ref="dialogsRef">
        <el-form-item label="用户名" prop="username"  label-width="120px">
          <el-input v-model="dialogRuleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码"  prop="password" label-width="120px">
          <el-input v-model="dialogRuleForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="120px">
          <el-input v-model="dialogRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile" label-width="120px">
          <el-input v-model="dialogRuleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- dialog-footer页脚部分 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateData">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改dialog部分 -->
    <el-dialog title="修改用户" :visible.sync="Visible">
      <el-form  
        :model="editMsg" 
        :rules="editRules"
        ref="editRef">
        <el-form-item label="用户名" label-width="120px">
          <el-input v-model="editMsg.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email"  label-width="120px">
          <el-input v-model="editMsg.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile"  label-width="120px">
          <el-input v-model="editMsg.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- dialog-footer页脚部分 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="Visible = false">取 消</el-button>
        <el-button type="primary" @click="editMessage">确 定</el-button>
      </div>
    </el-dialog>
    

    <!-- 分配角色部分 -->
    <el-dialog title="分配角色" 
      :visible.sync="disVisible"
       class="currentUser"
       @close="clearRoles"
      >
    <!-- 内容主题部分-->
      <p>当前用户：{{disMsg.username}}</p>
      <p>当前角色：{{disMsg.role_name}}</p>
      <p class="roles">
        分配新角色：
        <el-select v-model="roleId" placeholder="请选择">
          <el-option 
            v-for="item in disForm.roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"></el-option>
        </el-select>     
      </p>
    <!-- dialog-footer页脚部分 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="disVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitRoles">确 定</el-button>
    </div>
    </el-dialog>
  </div>  
</template>


<script>
export default {
  data() {
    //自定义验证email
    var validateEmail = (rule, value, callback) => {
      let reg=  /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if(!reg.test(value)){
        callback(new Error('请输入合法的邮箱'))
      }
      //在使用el-form的表单校验时，必须确保每个校验规则都调用的callback方法，否则会导致表单的validata方法无法进入回调函数。
      callback()
    };
    //自定义验证mobile
    var validateMobile = (rule, value, callback) => {
      let reg=  /^1[3|4|5|8][0-9]\d{4,8}$/;
      if(!reg.test(value)){
        callback(new Error('请输入合法的手机号'))
      }
      //在使用el-form的表单校验时，必须确保每个校验规则都调用的callback方法，否则会导致表单的validata方法无法进入回调函数。
      callback()
    };

    return {
     dialogRuleForm: {
        username:"",
        password:"",
        email:"",
        mobile:"", 
      },
      dialogFormVisible:false,
      disVisible:false,
      Visible:false,//修改部分的显示与隐藏
      queryobj: {
        //查询数据的参数
        query: "", //查询参数
        pagenum: 1, //当前页码
        pagesize: 5, //每页显示条数
      },
      //用户数据
      tableData: [],
      totalpage: 0, //总记录数
      dialogRules:{
        username:[
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' }
        ], 
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' }
          ,{ validator: validateEmail, trigger: 'blur' }
        ], 
        mobile:[
          { required: true, message: '请输入手机号', trigger: 'blur' }
         ,{ validator: validateMobile, trigger: 'blur' }
        ]
      },
      editMsg:{},//编辑信息
      disMsg:{},
      disForm:{
        roleList:[]
      },
      roleId:"",//与value中的数据做一个同步数据绑定
      editRules:{
          email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' }
          ,{ validator: validateEmail, trigger: 'blur' }
          ], 
          mobile:[
            { required: true, message: '请输入手机号', trigger: 'blur' }
          ,{ validator: validateMobile, trigger: 'blur' }
          ]
      }
    }

  },
  created() {
    //获取数据
    this.getTableData();
  },
  methods: {
    //获取table的数据
    async getTableData() {
      let {
        data: res,
      } = await this.$axios.get(
        "http://timemeetyou.com:8889/api/private/v1/users",
        { params: this.queryobj }
      );
      if (res.meta.status !== 200) {
        this.$message.error("获取管理员列表错误!");
      }
      this.tableData = res.data.users;
      this.totalpage = res.data.total;
      this.pagenum = res.pagenum;
    },
    //pagesize 改变时触发
    handleSizeChange(val) {
      this.queryobj.pagesize = val;
      this.getTableData();
    },
    //currentPage 改变时会触发
    handleCurrentChange(val) {
      this.queryobj.pagenum = val;
      this.getTableData();
    },
    //switch状态发生改变时触发
    async updateStatus(id, status) {
      let { data: res } = await this.$axios.put(
        `http://timemeetyou.com:8889/api/private/v1/users/${id}/state/${status}`
      );
      if (res.meta.status === 200) {
        this.$message.success("更新数据成功");
      }
    },
    //update数据时触发
    updateData() {
      this.$refs.dialogsRef.validate( async (valid)=>{
        if(valid){
          let {data:res} = await this.$axios.post("http://timemeetyou.com:8889/api/private/v1/users",this.dialogRuleForm) 
          if(res.meta.status === 201){
            this.$message.success("创建数据成功！")
          }
          this.dialogFormVisible = false
        }else{
          console.log("error Submit")
        }
      })      
    },
    //保存需要编辑的数据
    async saveEditMessage(id){
      //根据id查找数据
      let {data:res} =await this.$axios.get("http://timemeetyou.com:8889/api/private/v1/users/"+id)
      //不能一个属性一个属性的赋值，这样对象没有getter与setter
      this.editMsg = res.data;
      //打开editdialog
      this.Visible = true;
    },
    //编辑用户数据
    editMessage(){
      this.$refs.editRef.validate(async valid=>{
        if(valid){//表单验证
          let {data:res} = await this.$axios.put("http://timemeetyou.com:8889/api/private/v1/users/"+this.editMsg.id,{
            email:this.editMsg.email,
            mobile:this.editMsg.mobile
          })
          if(res.meta.status ===200){
            this.$message.success("更新成功！")
          }
          //重新渲染数据
          this.getTableData();
          this.Visible = false;
        }
      })
      
    },
    //删除用户数据
    async deleteMessage(id){
      let result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      }).catch(err=>err)

      if(result === "confirm"){//删除
        let {data:res} = await this.$axios.delete("http://timemeetyou.com:8889/api/private/v1/users/"+id)
          if(res.meta.status ===200){
            this.$message.success("删除成功！")
            //重新获取数据
            this.getTableData();
          }else{
            this.$message.error("该用户无法删除！")
          }
      }
      else{
        this.$message("已取消删除！")
      }
      
    },


    //分配角色
    async disRoles(data){
      this.disMsg.role_name=data.role_name
      this.disMsg.username=data.username
      this.disMsg.id = data.id
      //获取角色列表
      let {data:res} =await this.$axios.get("http://timemeetyou.com:8889/api/private/v1/roles")
      this.disForm.roleList = res.data;
      this.disVisible = true;
    },
    //提交分配角色信息
    async submitRoles(){
      if(!this.roleId){
        return this.$message.error("请选择要分配的角色！")
      }
      let {data:res} =await this.$axios.put(`http://timemeetyou.com:8889/api/private/v1/users/${this.disMsg.id}/role`,{rid:this.roleId})
      if(res.meta.status===200){
        this.$message.success("分配角色成功！")
        this.getTableData()
      }
        this.disVisible = false
    },
    clearRoles(){
      this.roleId ="";
      this.disMsg ={};
    }
  },
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}
.box-card {
  padding: 10px;
}
.content {
  margin-bottom: 15px;
}
.el-pagination {
  margin-top: 20px;
}
.el-table {
  font-size: 12px;
}
.currentUser p{
  margin-bottom: 15px;
}
.roles{
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.el-select-dropdown{
  top:223px !important;
}
</style>